<?php
/**
 * Created by PhpStorm.
 * User: liuxiaojie
 * Date: 2019-02-24
 * Time: 14:17
 */

namespace app\api\controller;

use app\model\JobWelfare;
use app\common\BaseLoginCustomer;

class Job extends BaseLoginCustomer {

    // 工作列表
    function index(){

        $page = $this->getParam('page', 1);
        $code = $this->getParam('code', 0);
        $cate_id = $this->getParam('cate_id', 0);
        $pay_id = $this->getParam('pay_id', '');
        $lat = $this->getParam('lat', 0);
        $lng = $this->getParam('lng', 0);
        $company_id = $this->getParam('company_id', 0);
        $keyword = $this->getParam('keyword', '');

        $where = [];
        $where1 = '';

        if($keyword){
            $company = db('company')->where(['name'=> ['like', "%{$keyword}%"], 'status'=> ['in', [3, 6]]])->column('id');
            if($company){
                $where['company_id'] = ['in', $company];
            }else{
                $where['name'] = ['like', "%{$keyword}%"];
            }
        }

        if($code){
            $where['area_tag'] = $code;
        }

        if($cate_id){
            $where['cate_id'] = $cate_id;
        }

        if($pay_id){

            $pay = db('job_pay')->where(['id'=> $pay_id])->field('min, max')->find();

            $where1 .= " (max between {$pay['min']} and {$pay['max']} or min between {$pay['min']} and {$pay['max']} ) ";

        }

        if($company_id){
            $where['company_id'] = $company_id;
        }

        $where['lat'] = $lat;
        $where['lng'] = $lng;


        $job = new \app\model\Job();
        $data = $job->lists($where, $where1, $page);
        $welfare = JobWelfare::allData();

        $result = [
            'list'=> $data,
            'welfare'=> array_column($welfare, 'name', 'id')
        ];

        return success($result);
    }

    // 工作详情
    function detail(){
        $id = $this->getParam('id', 0);
        $lat = $this->getParam('lat', 0);
        $lng = $this->getParam('lng', 0);

        $data = db('job j')
            ->join('company c', 'c.id = j.company_id')
            ->where(['j.id'=> $id])
            ->field("j.area_tag, j.company_id, j.pay_id, j.min, j.max, j.num, j.cate_id, j.name, j.pay, j.address, j.lat, j.lng, j.detail, (st_distance (point (j.lng, j.lat),point($lng,$lat) ) * 111195) AS distance, c.name as c_name, j.mobile, c.code as c_code, c.tel as c_tel, j.person, c.qrcode")
            ->find();

        if(intval($data['distance']) < 1000)
        {
            $data['distance'] = intval($data['distance']);
        }else{
            $data['distance'] = round(intval($data['distance'])/1000, 2).'千';
        }

        $weal = db('job_tag t')
            ->join('job_welfare w', "t.w_id = w.id")
            ->where(['t.job_id'=> $id])
            ->field('w.name, t.w_id, t.id')
            ->select();

        $data['welfare'] = $weal;
        return success($data);
    }
}